import {
  loginREQ,
  logoutREQ,
  personalREQ,
  refreshTokenREQ
} from '@/api/accounts'
import {
  getAuthToken,
  setAuthToken,
  removeAuthToken,
  getAuthRefreshToken,
  setAuthRefreshToken,
  removeAuthRefreshToken
} from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: '',
  name: '',
  username: '',
  authoritiesCode: [] // set 类型
}

const mutations = {
  SET_TOKEN: state => {
    state.token = getAuthToken()
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  },
  SET_AUTORITIES_CODE: (state, authorities) => {
    if (authorities && authorities.length > 0) {
      state.authoritiesCode = authorities
    } else {
      state.authoritiesCode = []
    }
  }
}

const actions = {
  login({ commit }, accountsInfo) {
    return new Promise((resolve, reject) => {
      loginREQ(accountsInfo)
        .then(data => {
          // commit('SET_TOKEN', access_token)
          setAuthToken(data.access_token, data.expires_in)
          setAuthRefreshToken(data.refresh_token)
          commit('SET_TOKEN')
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  resetLogin({ commit, state }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_NAME', '')
      commit('SET_USERNAME', null)
      commit('SET_AUTORITIES_CODE', null)
      removeAuthToken()
      removeAuthRefreshToken()
      resetRouter()
      location.reload()
      resolve()
    })
  },
  logout({ dispatch }) {
    return new Promise((resolve, reject) => {
      logoutREQ()
        .then(() => {
          dispatch('resetLogin')
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  personal({ commit, state }) {
    return new Promise((resolve, reject) => {
      personalREQ()
        .then(data => {
          commit('SET_NAME', data.name)
          commit('SET_USERNAME', data.username)
          commit('SET_AUTORITIES_CODE', data.authorities)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  refreshToken({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      if (!getAuthRefreshToken()) {
        reject({ data: null, message: '认证失败：令牌过期！', type: 'UNAUTHORIZED' })
        dispatch('resetLogin')
      } else {
        refreshTokenREQ(getAuthRefreshToken())
          .then(data => {
            setAuthToken(data.access_token, data.expires_in)
            setAuthRefreshToken(data.refresh_token)
            commit('SET_TOKEN')
            resolve(data)
          })
          .catch(error => {
            dispatch('resetLogin')
            reject(error)
          })
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
